package com.cate.utils;

import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @CreateTime: 2023/7/28
 * @Author: <==lhd==>
 * @Description: redis工具类
 */
@Component
public class RedisUtil {

    private static final long DEFAULT_EXPIRE = 24*60*60;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置键值对
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     */
    public void set(String key, Object value, long expireTime,TimeUnit timeUnit ){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),expireTime,timeUnit);
    }

    public void set(String key, Object value, long expireTime){
        set(key,value,expireTime, TimeUnit.SECONDS);
    }

    public void set(String key, Object value){
        set(key,value,DEFAULT_EXPIRE,TimeUnit.SECONDS);
    }

    public void setNoExpireTime(String key, String value){
        stringRedisTemplate.opsForValue().set(key,value);
    }



    /**
     * 获得对象
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T get(String key, Class<T> clazz) {
        String json = stringRedisTemplate.opsForValue().get(key);
        return JSONUtil.toBean(json,clazz);
    }


    /**
     * 获得字符串
     * @param key
     * @return
     */
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

//    public <T> List<T> getList(String keyPrefix){
//        stringRedisTemplate.opsForList().set("",1,"");
//    }


    /**
     * Hash 设置键值
     * @param key
     * @param map
     */
    public void putAll(String key, Map<String,Object> map){
        stringRedisTemplate.opsForHash().putAll(key,map);
    }

    /**
     * 删除键值
     * @param key
     */
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 清理缓存数据
     * @param pattern
     */
    public void cleanCache(String pattern){
        Set keys = stringRedisTemplate.keys(pattern);
        stringRedisTemplate.delete(keys);
    }
}
